import { getFuXiChuNengFnList} from "@src/spotMarketPrivateData/generate"
import { priviateAccount, userUnitid } from "@src/config/accountInfo"
import { AsyncRecursion, creatAsyncRecursion } from '@src/utils/asyncRecursion'
import { promisetTimeOut } from "@src/utils/common"
import { SMPrivateCodeConfig, SMPrivateCodes } from "@src/spotMarketPrivateData/data"

export type PrivateDataParams = {
  headers:HeadersInit,
  unitid?:string,
  certainDate?:string,
  dataDate?: number,
  actionFnList?: string[]
}
export const startGetSpotMarketPrivateData = async ({headers, unitid, certainDate, dataDate, actionFnList = []}:PrivateDataParams) => {
  console.log(
    `%c 现货市场私有数据数据`,
    'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
  )
  if(unitid !== userUnitid[priviateAccount])  {
    console.log(
      `%c 此用户不能获取现货市场私有数据 ${unitid}`,
      'color: red',
    )
    return Promise.resolve()
  }

  try {
    const fnList:Function[] = getFuXiChuNengFnList()

    let fnListFilter:Function[] = [...fnList]

    if(dataDate && actionFnList?.length) {
      console.error('startGetSpotMarketPrivateData的入参dataDate和actionFnList不能同时有值')
      return Promise.reject()
    }

    if(dataDate) {
      const dataDateFnNameList:string[] = []
      for(let key in SMPrivateCodeConfig) {
        if(SMPrivateCodeConfig?.[key as SMPrivateCodes]?.dataDate === dataDate) {
          const fnName = SMPrivateCodeConfig?.[key as SMPrivateCodes]?.fnName
          fnName && dataDateFnNameList.push(fnName)
        }
      }
      
      fnListFilter = fnList.filter((fn) => dataDateFnNameList.includes(fn.name))
    }

    if(actionFnList?.length) {
      fnListFilter = fnList.filter((fn) => actionFnList.includes(fn.name))
    }

    // 请求对应ReqType的所有数据
    let fnIndex = 0
    await creatAsyncRecursion(AsyncRecursion, {
      stepAsyncFnParamsList: fnListFilter,
      stepAsyncFn: async () => {
        await fnListFilter[fnIndex]?.({headers, unitid, certainDate})
      },
      stepCb: async () => {
        ++fnIndex
        await promisetTimeOut(100)
      }, // 每隔 发出请求，防反爬
      stepAsyncNum: 1,
      errBreak: false
    }).start()
    
  } catch(e) {
    console.error(e)
    return Promise.reject()
  }
}